<template>
  <div>
    <a-modal
      :maskClosable="false"
      :title="title"
      width="75vw"
      :bodyStyle="{
        padding: '0 24px',
      }"
      centered
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <a-row :gutter="10">
        <a-col :md="6" :sm="24">
          <a-card :bordered="false" style="width: 100%; height: 80vh; overflow-y: auto;">
            <div style="background: #fff; padding-left: 0px; height: 100%; overflow: auto">
              <!--<a-button type="primary" @click="allObj()">所有部门</a-button>-->
              <!-- <a-input-search @search="onSearch" style="width: 100%" placeholder="请输入部门名称" /> -->
              <!-- 树-->
              <template>
                <!--组织机构-->
                <a-directory-tree
                  selectable
                  :selectedKeys="selectedKeys"
                  :checkStrictly="true"
                  @select="onSelect"
                  :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                  :expandedKeys.sync="expandedKeys"
                  :treeData="departTree"
                />
              </template>
            </div>
          </a-card>
        </a-col>

        <a-col :md="18" :sm="24">
          <a-card
            :bordered="false"
            :bodyStyle="{
              padding: '20px 24px',
            }"
            style="width: 100%; height: 80vh; overflow-y: auto;"
          >
            用户姓名:
            <a-input-search
              :style="{ width: '180px', marginBottom: '15px' }"
              placeholder="请输入用户姓名"
              v-model="queryParam.realname"
              @search="searchByquery"
            ></a-input-search>
            <a-button @click="searchReset(1)" style="margin-left: 20px" icon="redo">重置</a-button>
            <a-table
              ref="table"
              rowKey="id"
              :components="drag(columns)"
              bordered
              :scroll="scrollTrigger"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :rowSelection="{
                selectedRowKeys: selectedRowKeys,
                onSelectAll: onSelectAll,
                onSelect: onSelectOne,
                onChange: onSelectChange,
                type: getType,
              }"
              @change="handleTableChange"
              class="j-table-force-nowrap"
              wrapClassName="ant-modal-cust-warp"
              :customRow="click"
            >
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { filterObj } from '@/utils/util'
import { queryDepartTreeList,queryRealDepartTreeList, queryUserByDepId, searchByKeywords } from '@/api/api'
import { getAction } from '@/api/manage'
import {tableDragResize} from '@/utils/draggable-multistage'

export default {
  name: 'SelectPostInputModal',
  components: {},
  props: ['multi','normalData'],
  mixins: [tableDragResize],
  data() {
    return {
      title: '选择人员',
      queryParam: {},
      urlList:"/api/erpmng/sys/user/list",
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
            title: '用户账号',
            align: 'center',
            width:100,
            dataIndex: 'username'
          },
          {
            title: '用户姓名',
            align: 'center',
            width:100,
            dataIndex: 'realname'
          },
          {
            title: '性别',
            align: 'center',
            dataIndex: 'sex',
            width:100,
            customRender: function (text) {
              if (text === 1) {
                return '男'
              } else if (text === 2) {
                return '女'
              } else {
                return text
              }
            }
          },
          {
            title: '手机',
            align: 'center',
            width:100,
            dataIndex: 'phone'
          },
          {
            title: '部门',
            align: 'center',
            width:300,
            dataIndex: 'orgCodeTxt'
          }
      ],
      url: {},
      dataSource: [],
      choseObj: [],
      departTree: [],
      selectedKeys: [],
      expandedKeys: [],
      iExpandedKeys: [],
      orgCode: '',
      loading: false,
      treeData: [],
      checkedKeys: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      scrollTrigger: { x: true },
      selectedRowKeys: [],
      selectionRows: [],
      visible: false,
      toggleSearchStatus: false
    }
  },
  created() {
    // this.loadData()
    // this.refresh()
    // 该方法触发屏幕自适应
    this.resetScreenSize()
    this.initSource()
  },
  computed: {
    // 计算属性的 getter
    getType: function () {
      return this.multi == true ? 'checkbox' : 'radio'
    }
  },
  watch:{
    normalData: {
      handler (val) {
        if (val) {
          this.queryParam.status = '1';
        }
      },
      immediate: true
    }
  },
  methods: {
    click(record, index) {
      var that = this
      return {
        on: {
          click: () => {
            let rowKeys = this.selectedRowKeys
            if (that.multi) {
              if (rowKeys.length > 0 && rowKeys.includes(record.id)) {
                rowKeys.splice(rowKeys.indexOf(record.id), 1)
                that.choseObj.splice(rowKeys.indexOf(record.id), 1)
              } else {
                rowKeys.push(record.id)
                that.choseObj.push(record)
              }
              this.selectedRowKeys = rowKeys
            } else {
              that.selectedRowKeys = []
              that.selectedRowKeys.push(record.id)
              that.choseObj = []
              that.choseObj.push(record)
            }
          }
        }
      }
    },
    add(selectObj, ids) {
      this.visible = true
      if (!this.departTree || !this.departTree.length) {
        this.refresh()
      }
      if (!this.dataSource || !this.dataSource.length) {
        this.loadData()
      }
      this.edit(selectObj, ids)
    },
    edit(selectObj, ids) {
      if (!ids) {
        this.selectedRowKeys = []
      } else {
        this.selectedRowKeys = ids
      }
      if (!selectObj) {
        this.selectionRows = []
      } else {
        this.selectionRows = selectObj
        this.choseObj = selectObj
      }
      if (ids == null && selectObj == null) {
        this.selectionRows = []
        this.choseObj = []
        this.selectedRowKeys = []
      }
    },
    async loadData(arg) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      // params.sysOrgCode = this.orgCode
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        await this.initQueryUserByDepId(this.selectedKeys)
      } else {
          var params = this.getQueryParams() // 查询条件
          if(this.normalData){
            params.status='1'
          }
          getAction(this.urlList, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
            if (this.orgCode === '') {
              // 第一次打开
            } else {
              for (var i = 0; i < this.dataSource.length; i++) {
                for (var j = 0; j < this.choseObj.length; j++) {
                  if (this.choseObj[j].id == this.dataSource[i].id) {
                    this.selectionRows.push(this.dataSource[i])
                    this.selectedRowKeys.push(this.dataSource[i].id)
                    break
                  }
                }
              }
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1)
            }
          }
        })
      }
    },
    loadTree() {
      var that = this
      that.treeData = []
      that.departTree = []
      if(this.normalData){
        queryRealDepartTreeList().then((res) => {
        if (res.success) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
            // 默认展开父节点
            this.expandedKeys = this.departTree.map(item => item.id)
          }

          this.loading = false
        }
      })
      }else{
        queryDepartTreeList().then((res) => {
        if (res.success) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
            // 默认展开父节点
            this.expandedKeys = this.departTree.map(item => item.id)
          }

          this.loading = false
        }
      })
      }
      
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      let str = 'id,'
      for (let a = 0; a < this.columns.length; a++) {
        str += ',' + this.columns[a].dataIndex
      }
      return str
    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected === true) {
        for (var a = 0; a < changeRows.length; a++) {
          this.choseObj.push(changeRows[a])
        }
      } else {
        for (var b = 0; b < changeRows.length; b++) {
          this.choseObj.splice(this.choseObj.indexOf(changeRows[b]), 1)
        }
      }
    },
    onSelectOne(record, selected) {
      if (selected === true) {
        if (this.multi) {
          // 多选
          this.choseObj.push(record)
        } else {
          // 单选
          this.choseObj = []
          this.choseObj.push(record)
        }
      } else {
        if (this.multi) {
          // 多选
          var index = -1
          for (var i = 0; i < this.choseObj.length; i++) {
            if (this.choseObj[i].id == record.id) {
              index = i
              break
            }
          }
          if (index >= 0) {
            this.choseObj.splice(index, 1)
          }
        } else {
          // 单选
          this.choseObj = []
        }
      }
    },
    initSource() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.choseObj = []
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    searchReset() {
      let that = this
      Object.keys(that.queryParam).forEach(function (key) {
        that.queryParam[key] = ''
      })
      this.selectedKeys = []
      that.loadData(1)
    },
    handleTableChange(pagination, filters, sorter) {
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleCancel() {
      this.selectionRows = []
      this.selectedRowKeys = []
      this.visible = false
    },
    handleOk() {
      this.$emit('choseObj', this.choseObj)
      this.handleCancel()
    },
    searchByquery() {
      this.loadData(1)
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    onSearch(value) {
      let that = this
      if (value) {
        searchByKeywords({ keyWord: value }).then((res) => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.loading = true
      this.loadTree()
    },
    onSelect(selectedKeys, e) {
      if (selectedKeys[0] != null) {
          this.initQueryUserByDepId(selectedKeys); // 调用方法根据选选择的id查询用户信息
          if (this.selectedKeys[0] !== selectedKeys[0]) {
            this.selectedKeys = [selectedKeys[0]];
          }
        }
      // if (this.selectedKeys[0] !== selectedKeys[0]) {
      //   this.selectedKeys = [selectedKeys[0]]
      // }
      // let record = e.node.dataRef
      // // this.selectionRows.push(record.id);
      // this.onClearSelected()
      // this.open(record)
    },
    // 根据选择的id来查询用户信息
    initQueryUserByDepId(selectedDepIds) {
      this.loading = true
      return queryUserByDepId({ id: selectedDepIds.toString(), realname: this.queryParam.realname }).then((res) => {
        if (res.success) {
          this.dataSource = res.result;
          this.ipagination.total = res.result.length;
        }
      }).finally(() => {
        this.loading = false
      })
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    open(record) {
      this.orgCode = record.orgCode
      this.loadData(1)
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    allObj() {
      this.selectedKeys = []
      this.onClearSelected()
      this.orgCode = null
      this.loadData(1)
    }
  }
}
</script>
<style scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px;
}

.ant-btn-danger {
  background-color: #ffffff;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

.anty-img-wrap {
  height: 25px;
  position: relative;
}

.anty-img-wrap > img {
  max-height: 100%;
}
</style>
